import { View, Form, Input, Button, Text, Image } from '@tarojs/components'
import { useState, useEffect, useRef } from 'react'
import Taro, { useDidShow, useDidHide } from '@tarojs/taro'
import { useAuth } from '../../contexts/AuthContext'
import { ui } from '../../utils/platform'
import './index.less'

// 导入图片
import avatarImg from '../../assets/login/Screenshot_2025-07-07-10-17-18-773_com.larus.nova.jpg'
import logoImg from '../../assets/logo.jpg'

export default function Login() {
  const [name, setName] = useState('')
  const [password, setPassword] = useState('')
  const [formError, setFormError] = useState('')
  const [showWechatDrawer, setShowWechatDrawer] = useState(false)
  const [wechatLoginStatus, setWechatLoginStatus] = useState('')
  // 使用ref来跟踪组件是否已挂载
  const isMounted = useRef(true)
  
  // 使用Auth Context
  const { isLoading, error, login, wechatLogin, clearError } = useAuth()
  
  // 组件挂载处理
  useEffect(() => {
    console.log('Login页面挂载')
    isMounted.current = true
    
    // 组件卸载时清理
    return () => {
      console.log('Login页面卸载')
      isMounted.current = false
    }
  }, [])
  
  // 使用Taro的页面生命周期钩子，处理页面显示和隐藏
  useDidShow(() => {
    console.log('Login页面显示')
    isMounted.current = true
    // 页面每次显示时清除错误
    clearError()
    setFormError('')
  })
  
  useDidHide(() => {
    console.log('Login页面隐藏')
    isMounted.current = false
  })
  
  // 当Context中的error变化时更新表单错误
  useEffect(() => {
    if (error && isMounted.current) {
      setFormError(error)
    }
  }, [error])

  const handleSubmit = async () => {
    // 添加日志便于调试
    console.log('准备登录', { name, password })
    
    if (!name || !password) {
      setFormError('用户名和密码不能为空')
      return
    }
    
    // 清除之前的错误
    setFormError('')
    clearError()
    
    try {
      console.log('调用login API')
      // 使用Context的login方法
      const result = await login(name, password)
      console.log('登录结果', result)
      
      // 检查是否成功并确保组件仍然挂载
      if (result && result.success === true) {
        console.log('登录成功，准备跳转')
        
        ui.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        })
        
        // 登录成功后跳转到首页 - 使用setTimeout确保toast显示完成
        setTimeout(() => {
          console.log('开始跳转到首页')
          ui.redirectTo({
            url: '/pages/index/index',
            success: () => console.log('跳转成功'),
            fail: (err) => console.error('跳转失败', err)
          })
        }, 1500)
      } else {
        console.error('登录结果不成功:', result)
        // 显示后端返回的具体错误信息
        const errorMessage = result?.message || result?.msg || '登录失败，请重试'
        setFormError(errorMessage)
      }
    } catch (err) {
      // 错误处理
      console.error('登录过程发生错误:', err)
      setFormError(err?.message || '登录失败，请重试')
    }
  }

  // 注册按钮点击处理
  const handleRegister = () => {
    ui.navigateTo({
      url: '/pages/register/index'
    })
  }

  // 微信登录处理
  const handleWechatLogin = () => {
    setShowWechatDrawer(true)
    setWechatLoginStatus('正在获取微信授权...')
    
    // 调用微信登录API
    Taro.login({
      success: async (res) => {
        console.log('微信登录成功，code:', res.code)
        if (res.code) {
          setWechatLoginStatus('正在验证登录信息...')
          
          try {
            // 使用Redux的微信登录方法
            const result = await wechatLogin(res.code)
            console.log('微信登录结果:', result)
            
            if (result && result.success) {
              if (result.isOldUser === 1) {
                // 老用户，直接登录成功
                setWechatLoginStatus('登录成功！')
                Taro.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 1500
                })
                
                setTimeout(() => {
                  setShowWechatDrawer(false)
                  Taro.redirectTo({
                    url: '/pages/index/index'
                  })
                }, 1500)
              } else {
                // 新用户，跳转到完善信息页面
                setWechatLoginStatus('检测到新用户，请完善信息')
                setTimeout(() => {
                  setShowWechatDrawer(false)
                  Taro.navigateTo({
                    url: '/pages/register/registerStep/index'
                  })
                }, 1500)
              }
            } else {
              console.error('微信登录失败:', result.message)
              const errorMessage = result?.message || result?.msg || '登录失败，请重试'
              setWechatLoginStatus(errorMessage)
              Taro.showToast({
                title: errorMessage,
                icon: 'error'
              })
            }
          } catch (error) {
            console.error('微信登录异常:', error)
            const errorMessage = error?.message || '登录失败，请重试'
            setWechatLoginStatus(errorMessage)
            Taro.showToast({
              title: errorMessage,
              icon: 'error'
            })
          }
        } else {
          console.error('登录失败！' + res.errMsg)
          setWechatLoginStatus('获取授权失败')
        }
      },
      fail: (err) => {
        console.error('微信登录失败:', err)
        setWechatLoginStatus('微信登录失败')
        Taro.showToast({
          title: '登录失败',
          icon: 'error'
        })
      }
    })
  }

  // 关闭微信登录抽屉
  const closeWechatDrawer = () => {
    setShowWechatDrawer(false)
    setWechatLoginStatus('')
  }

  return (
    <View className='login-container'>
      <View className='logo-container'>
        <Image 
          className='logo-image'
          src={logoImg} 
          mode='aspectFit'
        />
      </View>
      
      <View className='avatar-container'>
        <Image 
          className='avatar-image'
          src={avatarImg} 
          mode='aspectFill'
        />
      </View>
      
      <Form className='login-form' onSubmit={handleSubmit}>
        <View className='form-item'>
          <Input
            className='input'
            name='name'
            placeholder='请输入用户名'
            value={name}
            onInput={e => setName(e.detail.value)}
          />
        </View>
        
        <View className='form-item'>
          <Input
            className='input'
            name='password'
            placeholder='请输入密码'
            password
            value={password}
            onInput={e => setPassword(e.detail.value)}
          />
        </View>
        
        {formError && <Text className='error-message'>{formError}</Text>}
        
        <Button 
          className='login-button' 
          formType='submit'
          loading={isLoading}
          disabled={isLoading}
        >
          {isLoading ? '登录中...' : '登录'}
        </Button>
      </Form>
      
      <View className='bottom-buttons-container'>
        <View className='register-container' onClick={handleRegister}>
          <View className='register-icon'>
            <Text className='register-plus'>+</Text>
          </View>
          <Text className='register-text'>注册</Text>
        </View>
        
        <View className='wechat-login-container' onClick={handleWechatLogin}>
          <View className='wechat-login-icon'>📱</View>
          <Text className='wechat-login-text'>微信登录</Text>
        </View>
      </View>
      
      {showWechatDrawer && (
        <View className='wechat-drawer-mask' onClick={closeWechatDrawer}>
          <View className='wechat-drawer' onClick={(e) => e.stopPropagation()}>
            <View className='wechat-drawer-content'>
              <View className='wechat-drawer-header'>
                <Text className='wechat-drawer-title'>微信登录</Text>
                <Button className='close-btn' onClick={closeWechatDrawer}>×</Button>
              </View>
              <View className='wechat-drawer-body'>
                <View className='wechat-icon-large'>📱</View>
                <Text className='wechat-status'>{wechatLoginStatus}</Text>
                <View className='wechat-tips'>
                  <Text className='tips-text'>• 使用微信账号快速登录</Text>
                  <Text className='tips-text'>• 新用户需要完善个人信息</Text>
                </View>
              </View>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}